<template>
  <div id="FunctionModule">
    <Breadcrumb :content="content"></Breadcrumb>
    <div class="bodyContent skin-green">
      <Splitpanes style="height: 100%">
        <Pane :size="(800 / conWidth) * 100">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">模块</div>
              <vxe-input clearable placeholder="关键字查询" class="vxeInputSearch" v-model="keywords" @search-click="search" @keyup="keyup" type="search"></vxe-input>

              <vxe-button v-if="modulePoitPre.includes('XTGN005')" type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="handleSearch"></vxe-button>
              <vxe-button v-if="modulePoitPre.includes('XTGN001')" type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="handleAdd('')"></vxe-button>
              <vxe-button v-if="modulePoitPre.includes('XTGN004')" type="text" icon="vxe-icon-save" content="保存" :loading="saveLoading" class="button-blue" @click="saveList"></vxe-button>
              <vxe-button v-if="modulePoitPre.includes('XTGN003')" type="text" class="button-red" icon="vxe-icon-delete" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="modulTable">
            <vxe-table ref="moduleTable" align="left" border="inner" height="auto" class="mytable-scrollbar" :loading="showLoading" :data="moduleList" @current-change="moduleRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showIcon: false,
                showStatus: true
              }" :edit-rules="formRule" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="26" align="center"></vxe-column>
              <vxe-column type="seq" title="序号" width="30" align="left"></vxe-column>
              <vxe-column field="icon" title="图标" width="40" align="left" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <el-icon size="20" class="icon">
                    <component :is="row.icon"></component>
                  </el-icon>
                </template>

                <template #edit="{ row }">
                  <vxe-input v-model="row.icon" type="text" @focus.once="showSelectIocn" ref="reficon"></vxe-input>
                  <SelectIcon ref="refselectIcon" @SelectIcon="selectIcon1"></SelectIcon>
                </template>
              </vxe-column>
              <vxe-column field="code" title="编码" width="100" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.code" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="name" title="名称" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.name" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="bigIcon" title="大图标" width="100" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.bigIcon" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="sn" title="顺序号" min-width="80" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.sn" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="bigIconBgcolour" title="背景色" min-width="80" align="center">
                <template #default="{ row }">
                  <el-color-picker v-model="row.bigIconBgcolour" show-alpha :predefine="predefineColors" />
                </template>
              </vxe-column>
              <vxe-column field="baseModule" title="登录模块" min-width="80" align="center">
                <template #default="{ row }">
              <el-switch v-model="row.baseModule" inline-prompt active-text="是" inactive-text="否"></el-switch>
                </template>
              </vxe-column>
              <vxe-column field="baseUrl" title="路径" min-width="80" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.baseUrl" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
            <!-- <vxe-pager
              v-model:current-page="page.currentPage"
              v-model:page-size="page.pageSize"
              :total="page.totalResult"
              @page-change="pageChange"
              :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]"
            >
            </vxe-pager> -->
          </div>
        </Pane>
        <!-- 菜单 -->
        <Pane>
          <MenuList ref="refMenu"></MenuList>
        </Pane>
        <!-- <Pane size="30">
          <FunctionPoint ref="refPoint"></FunctionPoint>
        </Pane> -->
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import MenuList from './MenuList.vue';
import FunctionPoint from './FunctionPoint.vue';
import Breadcrumb from '../../../components/Breadcrumb.vue';
import VxePulldownSelection from '../../../components/VxePulldownSelection.vue';
import VxePulldownSelectIconfont from '../../../components/VxePulldownSelectIconfont.vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import SelectByDepList from '@/components/SelectByDepList.vue';
import SelectIcon from '../../../components/SelectIcon.vue';
let store = AppStore();
let { proxy }: any = getCurrentInstance();

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 子组件ref名称
let refselectIcon = ref(null);

// 获取模块id
const moduleId = localStorage.getItem('moduleId');

// let refPoint: any = ref(null);
let refMenu: any = ref(null);

// 分页
let page = reactive({
  currentPage: 1,
  pageSize: 10000,
  totalResult: 0
});

// 当前屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
// 页面标题
let content = ref('功能模块');
// loding
let loading = ref(false);

// 弹框表单状态
let showDialog = ref(false);
// 用户输入关键字
let keywords = ref('');

// 点击的模块id  传递个子组件
// let moduleId = ref('');
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
let modulePointMap = store.userInfo.modulePointMap;

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存

//**判断为空*/
let IsEmpty = (value: any) => {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
};

// 常用颜色
const predefineColors = ref(['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585', 'rgba(255, 69, 0, 0.68)', 'rgb(255, 120, 0)', 'hsv(51, 100, 98)', 'hsva(120, 40, 94, 0.5)', 'hsl(181, 100%, 37%)', 'hsla(209, 100%, 56%, 0.73)', '#c7158577']);

onMounted(() => {
  getModuleList();
  getModulePointMap();
});

// 表格规则
let formRule = ref({
  code: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到32个字符',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
});
function getModulePointMap() {
  if (Object.keys(modulePointMap).includes(moduleId)) {
    modulePoitPre.push(...modulePointMap[moduleId]);
  }
}
// 模块功能表格数据
let moduleList: any = reactive([]);

// 请求模块表格数据
function getModuleList() {
  showLoading.value = true;
  let modulePageParam = {
    params: {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      keywords: keywords.value
    }
  };
  moduleList.length = 0; //放入数据前清空数组
  proxy.$http.get('/api/sys/getPageModules', modulePageParam).then((res: any) => {
    if (res.status.code === 1) {
      showLoading.value = false;
      // console.log('模块数据列表', res.status.code);
      page.totalResult = res.data.modulePageList.total;
      moduleList.push(...res.data.modulePageList.records);
      moduleRowClick({ row: moduleList[0], rowIndex: 0 });
      // VXETable.modal.message({ content: res.status.msg, status: 'success' });
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}

// 当前选中行的下标
let clickIndex = null;

// 点击行
function moduleRowClick({ row, rowIndex }) {
  clickIndex = rowIndex;
  // console.log(clickIndex, '当前选中行的下标');

  let $Xtable = proxy.$refs.moduleTable;
  $Xtable.setCurrentRow(row);
  if (!IsEmpty(row.id)) {
    refMenu.value.initPage(row.id); //调用菜单组件方法
  }
}
// 点击刷新
function handleSearch() {
  getModuleList();
}
let moduleTable = ref();
// 点击新增
async function handleAdd(row: any) {
  // // clearForm();
  // const $table = moduleTable.value;
  // if ($table) {
  //   // $table.setAllRowExpand(true);
  //   // 获取新增的数据记录
  //   const record = {
  //     code: '',
  //     name: '',
  //     icon: '', //图标
  //     bigIcon: '', //大图标地址
  //     sn: '', //排序号
  //     id: ''
  //   };
  //   //departList.push(record);
  //   $table.loadData(moduleList);
  //   const { row: newRow } = await $table.insertAt(record, -1);
  //   // 设置编辑行
  //   await $table.setEditRow(record);
  //   if (row) {
  //     await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
  //   }
  // }

  const record = {
    code: '',
    name: '',
    icon: '', //图标
    bigIcon: '', //大图标地址
    sn: moduleList.length + 1, //排序号
    id: ''
  };
  moduleList.push(record);
}

// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.moduleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows.length > 1) {
    VxeMessage('只能删除一条数据', VxeNotifyType.warning);
    return;
  }
  if (selectRows <= 0) {
    // VXETable.modal.message({ content: `请勾选要删除的数据`, status: 'warning' });
    VxeMessage('请勾选要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('确定删除此条用户数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        proxy.$http
          .delete('/api/sys/deleteModule/' + selectRows[0].id)
          .then((res: any) => {
            if (res.data == null) {
              // VXETable.modal.message({ content: res.status.msg, status: 'warning' });

              VxeMessage('删除模块失败', VxeNotifyType.error);
            } else {
              VxeMessage('删除模块成功', VxeNotifyType.success);
              getModuleList();
            }
          })
          .catch((err: any) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      });
  }
}

// 点击修改保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  let $Xtable = proxy.$refs.moduleTable;
  // console.log($Xtable);

  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    // const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
    //   return m.id === '';
    // });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = moduleList.filter((e: any) => {
      return e.id === '';
    });

    // console.log('模块', updateRecords);

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      proxy.$http
        .post('/api/sys/editModule', moduleAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            // VXETable.modal.message({ content: '修改成功', status: 'success' });
            VxeMessage('修改成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          // VXETable.modal.message({ content: '修改异常', status: 'error' });
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    // 新增
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      proxy.$http
        .post('/api/sys/addModule', moduleAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            // VXETable.modal.message({ content: '创建成功', status: 'success' });
            VxeMessage('创建成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          // VXETable.modal.message({ content: '创建异常', status: 'error' });
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });

    setTimeout(() => {
      getModuleList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

// 关键字搜索
function search() {
  moduleList.length = 0;
  proxy.$http.get('/api/sys/getModuleList', { params: { keywords: keywords.value } }).then((res: any) => {
    // console.log('数据列表', res.data.moduleList);
    moduleList.push(...res.data.moduleList);
  });
}

function keyup(e: any) {
  if (e.$event.code == 'Enter') {
    search();
  }
}

// 点击下一页
function pageChange(val: any) {
  page.currentPage = val.currentPage;
  getModuleList();
}

// 图标组件选中事件
function ConfirmByClick(data, row, fieldName, rowIndex = null, column = null) {
  if (IsEmpty(rowIndex) || IsEmpty(column)) {
    // console.log('rowIndex', rowIndex);
    // console.log('data', data);
    // console.log('模块数据', moduleList);
    // console.log('fieldName', fieldName);
    // console.log('row', row);
    moduleList[rowIndex].icon = data;
    if (fieldName === 'iconPath' && IsEmpty(row.selectedIcon)) {
      proxy.form.selectedIconPath = data;
    }
  } else {
    moduleList[rowIndex][fieldName] = data;
    if (fieldName === 'iconPath' && IsEmpty(row.icon)) {
      moduleList[rowIndex].icon = data;
    }
  }
}

// //选中图标组件选中事件
// function ConfirmByClick1(data, row, fieldName, rowIndex = null, column = null) {
//   if (IsEmpty(rowIndex) || IsEmpty(column)) {
//     proxy.form[fieldName] = data;
//     if (fieldName === 'iconPath' && IsEmpty(row.selectedIcon)) {
//       proxy.form.selectedIconPath = data;
//     }
//   } else {
//     // console.log('fieldName', rowIndex);
//     // console.log('data', data);
//     // console.log('模块数据', moduleList);
//     // console.log('fieldName', fieldName);
//     // console.log('row', row);
//     moduleList[rowIndex][fieldName] = data;
//     if (fieldName === 'iconPath' && IsEmpty(row.selectedIconPath)) {
//       moduleList[rowIndex].selectedIcon = data;
//     }
//   }
// }

// 组件选中图标

function selectIcon1(icon: any) {
  moduleList[clickIndex].icon = icon;
  setTimeout(() => {
    proxy.$refs.reficon.blur();
  }, 100);
}

// function selectIcon2(icon) {
//   form.icon = icon;
// }

// 点击放大镜打开组件
function showSelectIocn() {
  refselectIcon.value.initPage(true);
  // console.log(refselectIcon.value.initPage);
}
</script>
<style lang="scss" scoped>
#FunctionModule {
  height: 100%;
  width: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 左边表格
    .modulTable {
      height: calc(100% - 39px);
      background-color: $base-white;
    }
  }
}
</style>
